#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int ticket=100;
pthread_mutex_t mutex;

void* scalpers(void* arg)
{
  while(1)
  {
    //添加互斥锁
    pthread_mutex_lock(&mutex);
    if(ticket>0)
    {
      printf("scalpers:%d----get ticket:%d\n",(int)arg,ticket);
      ticket--;

      //接触互斥锁
      pthread_mutex_unlock(&mutex);

    }else 
    {
      printf("scalpers:%d----complete the mission\n",(int)arg);
     pthread_mutex_unlock(&mutex);
      pthread_exit(NULL);
      // pthread_cancel(tid[(int)arg]);
    }
  }

}


int main()
{

  pthread_t tid[4];
  int ret,i,j ;
  //互斥锁的初始化
  pthread_mutex_init(&mutex,NULL);
  for(i=0;i<4;i++)
  {
    ret=pthread_create(&tid[i],NULL,scalpers,(void*)i);
    if(ret!=0)
    {
      printf("creat thread error\n");
      return -1;
    }
  }
  
  for(j=0;j<4;j++)
  {
    pthread_join(tid[j],NULL);
  }

  //互斥锁的销毁
  pthread_mutex_destroy(&mutex);
  return 0;
}
